package com.yoku.view.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Desc:
 * Date: 2016/12/13
 */

@Component
@Slf4j
public class LoginInterceptor extends WebMvcConfigurerAdapter implements HandlerInterceptor {

    public static final String USER_ID = "userId";

    //继承WebMvcConfigurerAdapter 重写addInterceptors方法,注册Interceptor.
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor());
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //判断链接是否登录,  查询白名单.
        httpServletRequest.getMethod();
        httpServletRequest.getSession().getAttribute(USER_ID);
        return true;
//        System.out.println("==================");
//        if (httpServletRequest.getParameter("pageNo") != null){
//            return true;
//        }
//
//        //请求重定向到登录页面, 并返回登录后跳转Url
//        httpServletResponse.sendRedirect("/api/user/page?pageNo=1&pageSize=2" + "&target=" + httpServletRequest.getRequestURL());
//        //httpServletRequest.getRequestDispatcher("/api/user/page?pageNo=1&pageSize=2").forward(httpServletRequest, httpServletResponse);
//        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("1111111111111");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("2222222222");
    }
}
